<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { cancelOrderAPI, getPayBySnAPI } from '@/apis/order'
import { ElMessage } from 'element-plus'

const route = useRoute()
// const router = useRouter()
const orderSn = computed(() => route.query.orderSn || '')
const paymentExpireKey = computed(() => `paymentExpire_${orderSn.value}`)

// 订单信息
const orderInfo = ref({
  totalAmount: 0,
  status: 0
})

// 倒计时相关
const countdown = ref(2 * 60) // 15分钟倒计时（单位：秒）
let countdownTimer = null

// 格式化时间显示
const formatTime = computed(() => {
  const minutes = Math.floor(countdown.value / 60)
  const seconds = countdown.value % 60
  return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
})

// 初始化订单数据
const initOrderData = async () => {
  try {
    // 优先使用路由参数中的金额
    if (route.query.totalPrice) {
      orderInfo.value.totalAmount = parseFloat(route.query.totalPrice)
      startCountdown()
      return
    }

    // 从API获取订单详情
    if (orderSn.value) {
      const res = await getPayBySnAPI(orderSn.value)
      orderInfo.value = res.data
      startCountdown()
    } else {
      ElMessage.error('缺少订单信息')
    }
  } catch (error) {
    ElMessage.error('订单加载失败: ' + (error.response?.data?.message || error.message))
  }
}

// 启动倒计时
const startCountdown = () => {
  // 尝试从本地存储恢复倒计时
  const storedExpireTime = localStorage.getItem(paymentExpireKey.value)
  const now = Math.floor(Date.now() / 1000)

  if (storedExpireTime) {
    const remaining = parseInt(storedExpireTime) - now
    countdown.value = Math.max(0, remaining)
  } else {
    // 设置新的15分钟倒计时
    const expireTime = now + 2 * 60
    localStorage.setItem(paymentExpireKey.value, expireTime.toString())
    countdown.value = 2 * 60
  }

  // 启动定时器
  countdownTimer = setInterval(() => {
    countdown.value--

    // 倒计时结束处理
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      handleOrderExpiration()
    }
  }, 1000)
}

// 处理订单过期
const handleOrderExpiration = async () => {
  try {
    if (orderSn.value) {
      // await cancelOrderAPI(orderSn.value)
      ElMessage.warning('订单已自动取消')
    }
  } catch (error) {
    console.error('订单取消失败:', error)
  } finally {
    localStorage.removeItem(paymentExpireKey.value)
  }
}

// 处理支付宝支付
const handleAliPay = async () => {
  try {
    if (!orderSn.value) {
      ElMessage.error('订单号无效')
      return
    }

    if (countdown.value <= 0) {
      ElMessage.warning('订单已超时，请重新下单')
      return
    }
    console.log(orderSn.value)

    const res = await getPayBySnAPI(orderSn.value)

    // 1. 创建空白窗口
    const payWindow = window.open('', '_blank')
    if (!payWindow) {
      ElMessage.warning('请允许弹出窗口完成支付')
      return
    }

    // 2. 分阶段写入内容（避免浏览器拦截）
    payWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>支付跳转中...</title>
          <style>
            body {
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100vh;
              font-family: Arial, sans-serif;
              background-color: #f5f7fa;
            }
            .loader {
              text-align: center;
              padding: 30px;
              background: white;
              border-radius: 10px;
              box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            }
            .spinner {
              border: 4px solid rgba(0, 0, 0, 0.1);
              border-radius: 50%;
              border-top: 4px solid #3498db;
              width: 40px;
              height: 40px;
              animation: spin 1s linear infinite;
              margin: 0 auto 20px;
            }
            @keyframes spin {
              0% { transform: rotate(0deg); }
              100% { transform: rotate(360deg); }
            }
          </style>
        </head>
        <body>
          <div class="loader">
            <div class="spinner"></div>
            <p>正在连接支付系统，请稍候...</p>
          </div>
        </body>
      </html>
    `)
    payWindow.document.close()

    // 3. 延迟写入真实内容
    setTimeout(() => {
      try {
        console.log('页面：'+res)
        payWindow.document.open()
        payWindow.document.write(res)
        payWindow.document.close()
      } catch (e) {
        console.error('支付窗口写入失败:', e)
        payWindow.close()
        ElMessage.error('支付窗口打开失败，请重试')
      }
    }, 300)

  } catch (err) {
    ElMessage.error(`支付失败: ${err.message}`)
    console.error('支付请求错误:', {
      response: err.response?.data,
      error: err.stack
    })
  }
}

// 清理工作
onUnmounted(() => {
  if (countdownTimer) clearInterval(countdownTimer)
})

onMounted(initOrderData)
</script>

<template>
  <div class="xtx-pay-page">
    <div class="container">
      <!-- 付款信息 -->
      <div class="pay-info">
        <span class="icon iconfont icon-queren2"></span>
        <div class="tip">
          <p>订单提交成功！请尽快完成支付。</p>
          <p v-if="countdown > 0">
            支付还剩 <span class="countdown">{{ formatTime }}</span>, 超时后将取消订单
          </p>
          <p v-else class="expired-text">订单已超时，请重新下单</p>
        </div>
        <div class="amount">
          <span>应付总额：</span>
          <span class="price">¥{{ orderInfo.totalAmount?.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="pay-type">
        <p class="head">选择支付方式</p>
        <div class="item">
          <p>支付宝支付</p>
          <a
              class="btn alipay"
              :class="{ disabled: countdown <= 0 }"
              @click="handleAliPay"
          ></a>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.xtx-pay-page {
  margin-top: 20px;
  min-height: 70vh;
  display: flex;
  align-items: center;
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.pay-info {
  display: flex;
  align-items: center;
  padding: 30px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 30px;

  .icon {
    font-size: 60px;
    color: #1dc779;
    margin-right: 20px;
  }

  .tip {
    flex: 1;

    p {
      margin: 8px 0;
      font-size: 16px;

      &:first-child {
        font-size: 18px;
        font-weight: 500;
        color: #333;
      }
    }

    .countdown {
      font-weight: bold;
      color: #e6a23c;
      font-family: monospace;
      font-size: 18px;
    }

    .expired-text {
      color: #f56c6c;
      font-weight: 500;
    }
  }

  .amount {
    min-width: 200px;
    text-align: right;

    span {
      display: block;
      margin-bottom: 5px;

      &:first-child {
        color: #666;
      }

      &.price {
        font-size: 24px;
        color: #cf4444;
        font-weight: bold;
      }
    }
  }
}

.pay-type {
  .head {
    font-size: 18px;
    font-weight: 500;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
  }

  .item {
    margin-bottom: 25px;

    p {
      font-size: 16px;
      margin-bottom: 15px;
      color: #333;
    }
  }

  .btn {
    display: inline-block;
    width: 180px;
    height: 60px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    text-align: center;
    line-height: 60px;
    margin-right: 15px;
    cursor: pointer;
    transition: all 0.3s;
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    background-image: url(https://img.alicdn.com/tfs/TB1Gf2jGpzqK1RjSZFHXXb3CpXa-260-120.png);
    background-color: #009fe8;
    border-color: #009fe8;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }

    &.disabled {
      opacity: 0.6;
      cursor: not-allowed;
      filter: grayscale(80%);

      &:hover {
        transform: none;
        box-shadow: none;
      }
    }
  }
}

@media (max-width: 768px) {
  .pay-info {
    flex-direction: column;
    text-align: center;

    .icon {
      margin-right: 0;
      margin-bottom: 15px;
    }

    .amount {
      margin-top: 20px;
      text-align: center;
      width: 100%;
    }
  }

  .btn {
    width: 100%;
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>